<template>
  <div class="area">
    <div class="status">
      <span>正确:</span>
      <span>{{ correctCount }}</span>
      <span>错误:</span>
      <span>{{ errorCount }}</span>
    </div>
    <div class="question">
      <span>{{ multiplicand }}</span>×<span>{{ multiplier }}</span>=
      <input v-model="inputRes" type="text" />
    </div>
    <div class="answer">
      <NumberKeyboard @ok="testResult" @input="handlerInput" @delete="handlerDelete"></NumberKeyboard>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

import NumberKeyboard from './NumberKeyboard.vue'

// 被乘数
const multiplicand = ref(1)
// 乘数
const multiplier = ref(1)


const initQuestion = () => {
  multiplicand.value = Math.floor(Math.random() * 9) + 1
  multiplier.value = Math.floor(Math.random() * 9) + 1
}

onMounted(() => {
  initQuestion()
})

const result = computed(() => {
  return multiplicand.value * multiplier.value
})

const correctCount = ref(0)

const errorCount = ref(0)

const inputRes = ref('')

const tip = ref('')

const emits = defineEmits<{
  (e: 'play', file: string): void
}>()

// const injectPlay = inject('play') as (file: string) => void

const testResult = () => {
  if (inputRes.value === '') {
    tip.value = '请输入答案'
    // speak(tip.value)
    // injectPlay('emptyTip.mp3')
    emits('play', 'emptyTip.mp3')
    return
  }
  try {
    const numberRes = Number(inputRes.value)
    if (numberRes === result.value) {
      correctCount.value++
      // speak(correctSpeaks[Math.floor(Math.random() * correctSpeaks.length)])
      emits('play', `okSound${Math.floor(Math.random() * 5)}.mp3`)
      // injectPlay(`okSound${Math.floor(Math.random() * 5)}.mp3`)
      initQuestion()
      inputRes.value = ''
    } else {
      errorCount.value++
      // speak(errorSpeaks[Math.floor(Math.random() * errorSpeaks.length)])
      // injectPlay(`errorSound${Math.floor(Math.random() * 4)}.mp3`)
      emits('play', `errorSound${Math.floor(Math.random() * 4)}.mp3`)
      inputRes.value = ''
    }
  } catch (e) {
    tip.value = '请输入数字'
  }
}

const handlerInput = (num: number) => {
  inputRes.value += num.toString()
}

const handlerDelete = () => {
  inputRes.value = inputRes.value.slice(0, -1)
}

</script>

<style scoped lang="scss">
.status {
  font-size: 1.2em;
  font-weight: 600;
  margin-top: 20px;

  span {
    margin-right: 10px;
  }
}

.question {
  font-size: 30px;
  font-weight: 600;
  margin-top: 20px;
  margin-bottom: 20px;

  input {
    outline: none;
    border: 1px solid #ccc;
    font-size: 30px;
    font-weight: 600;
    width: 80px;
    border-radius: 5px;
    text-align: center;
  }
}

.answer {
  text-align: center;


}
</style>